package com.wechat.android.app.ui.bottom;


import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.czy.otherlib.swipetoloadlayout.OnRefreshListener;
import com.czy.otherlib.swipetoloadlayout.SwipeToLoadLayout;
import com.easemob.cases.MessageHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.wechat.android.app.R;
import com.wechat.android.app.adapter.BaseRecyclerAdapter;
import com.wechat.android.app.adapter.MessageContactsAdapter;
import com.wechat.android.app.callback.RecycleViewDivider;
import com.wechat.android.app.callback.RecyclerHeadersDecoration;
import com.wechat.android.app.db.UserHelper;
import com.wechat.android.app.entity.MessageContactsModel;
import com.wechat.android.app.global.Constants;
import com.wechat.android.app.rxbus.RxBus;
import com.wechat.android.app.rxbus.Subscribe;
import com.wechat.android.app.rxbus.ThreadMode;
import com.wechat.android.app.rxbus.event.CommonEvent;
import com.wechat.android.app.ui.BaseFragment;
import com.wechat.android.app.ui.ChatActivity;
import com.wechat.android.app.ui.message.NewFriendsMsgActivity;
import com.wechat.android.app.utils.MyLog;
import com.wechat.android.app.utils.PhoneUtils;
import com.wechat.android.app.utils.disk.DiskLruCacheHelper;
import com.wechat.android.app.utils.pinyin.CharacterParser;
import com.wechat.android.app.widget.CustomFontTextView;
import com.wechat.android.app.widget.RecyclerSideBar;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by yang on 2018/1/12.
 * 联系人-
 */

public class ContactFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH_COMPLETE:
                    getContactData();
                    break;

            }
            return false;
        }


    });
    private static final String TAG = "ContactFragment";
    private static final int REFRESH_COMPLETE = 0X110;
    @BindView(R.id.nsv_message_contacts_tips)
    NestedScrollView nsvNoneTips;
    @BindView(R.id.tv_contact_tips)
    CustomFontTextView tvContactTips;
    @BindView(R.id.refresh_target)
    RecyclerView rvContactsMember;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout mSwipeLayout;
    @BindView(R.id.tv_message_contacts_dialog)
    TextView tvContactsDialog;
    @BindView(R.id.rvs_message_contacts_sidebar)
    RecyclerSideBar rvsContactsSideBar;
    @BindView(R.id.ll_frameLayout)
    FrameLayout llFrameLayout;
    @BindView(R.id.tv_new_friend)
    CustomFontTextView tvNewFriend;
    private CharacterParser characterParser;
    private MessageContactsComparator pinyinComparator;
    private MessageContactsAdapter mAdapter;
    private List<MessageContactsModel> mContactsList = new ArrayList<>();
    private RecyclerHeadersDecoration headersDecor = null;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_message_contants;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        RxBus.getDefault().register(this);
        getToolbarTitle().setText("\uD81B\uDF50\uD81B\uDF0A\uD81B\uDFA8\uD81B\uDF50\uD81B\uDF2F\uD81B\uDFC4\uD81B\uDFBE\uD81B\uDF3D\uD81B\uDFD3\uD81B\uDF16\uD81B\uDF54\uD81B\uDF50\uD81B\uDF37\uD81B\uDFD1");
        tvNewFriend.setText("\uD81B\uDF3D\uD81B\uDFD3\uD81B\uDF16\uD81B\uDF54\uD81B\uDF43\uD81B\uDFA0\uD81B\uDF2F\uD81B\uDF51\uD81B\uDFC7");
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        characterParser = CharacterParser.getInstance();
        pinyinComparator = new MessageContactsComparator();

        rvsContactsSideBar.setOnTouchingLetterChangedListener(new RecyclerSideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                int position = mAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    rvContactsMember.scrollToPosition(position);
                }

            }
        });


        mAdapter = new MessageContactsAdapter(getContext(), mContactsList, true, false);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        rvContactsMember.setLayoutManager(layoutManager);
        rvContactsMember.setAdapter(mAdapter);
        if (headersDecor != null) {
            rvContactsMember.removeItemDecoration(headersDecor);
        }
        headersDecor = new RecyclerHeadersDecoration(mAdapter);
        rvContactsMember.addItemDecoration(headersDecor);
        rvContactsMember.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));

        //   setTouchHelper();
        mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                headersDecor.invalidateHeaders();
            }
        });

        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<MessageContactsModel>() {
            @Override
            public void onItemClick(int position, MessageContactsModel messageContacts, View view) {
                String imKey = messageContacts.getImKey();
                EaseUser easeUser = new EaseUser(imKey);
                easeUser.setNick(messageContacts.getName());
                easeUser.setAvatar(messageContacts.getLogo());
                MessageHelper.getInstance().saveContact(easeUser);
                Intent msgIntent = new Intent(mContext, ChatActivity.class);
                msgIntent.putExtra(EaseConstant.EXTRA_USER_ID, imKey);
                startActivity(msgIntent);
            }
        });

        mAdapter.setDelFriendOnClick(new MessageContactsAdapter.OnDelFriendsListener() {
            @Override
            public void onDelFriendOnClick(MessageContactsModel data, int position) {
                delFriend(data.getImKey());
                mAdapter.remove(position);
                mAdapter.notifyDataSetChanged();
            }
        });


        rvsContactsSideBar.setMaxHeight(20);
        rvsContactsSideBar.setTextView(tvContactsDialog);

        mSwipeLayout.setOnRefreshListener(this);
        onRefresh();


    }

    private void getContactData() {
        mMProgressDialog.showNoText();
        EasyHttp.post(Constants.API_GETUSERLIST)
                .params("imKey", UserHelper.getInstance().getUserInfoModel(getActivity()).getImKey())
                .timeStamp(true)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();

                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.e("yang", e.toString());

                        mMStatusDialog.show("\uD81B\uDF1E\uD81B\uDFA9\uD81B\uDF04\uD81B\uDF7B\uD81B\uDF2F\uD81B\uDF51\uD81B\uDF62\uD81B\uDF3D\uD81B\uDF54\uD81B\uDF16\uD81B\uDF60", null);
                    }

                    @Override
                    public void onSuccess(String result) {
                        MyLog.e("yang", "通讯录列表==" + result);
                        String data = PhoneUtils.checkResponseFlag(getActivity(), result);
                        if (data != null) {
                            Gson gson = new Gson();
                            mContactsList = gson.fromJson(data, new TypeToken<List<MessageContactsModel>>() {
                            }.getType());
                            for (int i = 0; i < mContactsList.size(); i++) {
                                String pinyin = characterParser.getSelling(mContactsList.get(i).getName());
                                String sortString = pinyin.substring(0, 1).toUpperCase();
                                if (sortString.matches("[A-Z]")) {
                                    mContactsList.get(i).setSortLetters(sortString.toUpperCase());
                                } else {
                                    mContactsList.get(i).setSortLetters("#");
                                }
                                if (!TextUtils.isEmpty(mContactsList.get(i).getImKey())) {
                                    EaseUser easeUser = new EaseUser(mContactsList.get(i).getImKey());
                                    easeUser.setNick(mContactsList.get(i).getName());
                                    easeUser.setAvatar(mContactsList.get(i).getLogo());
                                    easeUser.setEmployeeId("" + mContactsList.get(i).getUserId());
                                    easeUser.setPhone(mContactsList.get(i).getPhone());
                                    MessageHelper.getInstance().saveContact(easeUser);
                                }

                            }
                            Collections.sort(mContactsList, pinyinComparator);
                            mAdapter.setList(mContactsList);
                            rvsContactsSideBar.setSortLetter(mAdapter.getArraySortLetters());
                            mSwipeLayout.setRefreshing(false);
                            checkTips();
                        }
                    }
                });


    }


    private void checkTips() {
        MyLog.e("yang", "mAdapter.getItemCount()==" + mAdapter.getItemCount());
        if (mAdapter.getItemCount() > 0) {
            nsvNoneTips.setVisibility(View.GONE);
            llFrameLayout.setVisibility(View.VISIBLE);
        } else {
            nsvNoneTips.setVisibility(View.VISIBLE);
            llFrameLayout.setVisibility(View.GONE);
            tvContactTips.setText("\uD81B\uDF50\uD81B\uDF0A\uD81B\uDFA8\uD81B\uDF50\uD81B\uDF2F\uD81B\uDFC4\uD81B\uDFBE\uD81B\uDF3D\uD81B\uDFD3\uD81B\uDF16\uD81B\uDF54\uD81B\uDF50\uD81B\uDF37\uD81B\uDFD1\uD81B\uDF1E\uD81B\uDF68\uD81B\uDF2F\uD81B\uDFAA");
        }
    }

    public class MessageContactsComparator implements Comparator<MessageContactsModel> {

        public int compare(MessageContactsModel o1, MessageContactsModel o2) {
            if (o1.getSortLetters().equals("@")

                    || o2.getSortLetters().equals("#")) {
                return -1;
            } else if (o1.getSortLetters().equals("#")
                    || o2.getSortLetters().equals("@")) {
                return 1;
            } else {
                return o1.getSortLetters().compareTo(o2.getSortLetters());
            }
        }

    }


    public void onRefresh() {
        mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 500);

    }

    @OnClick({R.id.ll_new_friend})
    public void viewOnClick(View view) {
        startActivity(new Intent(getActivity(), NewFriendsMsgActivity.class));
    }

    private void delFriend(String friendImkey) {
        mMProgressDialog.showNoText();
        HttpParams params = new HttpParams();
        params.put("imKey", UserHelper.getInstance().getUserInfoModel(getActivity()).getImKey());
        params.put("friendImkey", friendImkey);
        EasyHttp.post(Constants.API_DELFRIENDSINGER)
                .params(params)
                .timeStamp(true)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.e("yang", "e==" + e.toString());
                        mMStatusDialog.show("\uD81B\uDF1E\uD81B\uDFA9\uD81B\uDF04\uD81B\uDF7B\uD81B\uDF2F\uD81B\uDF51\uD81B\uDF62\uD81B\uDF3D\uD81B\uDF54\uD81B\uDF16\uD81B\uDF60", null);
                    }

                    @Override
                    public void onSuccess(String result) {
                        MyLog.e("yang", "删除好友成功==" + result);
                        String data = PhoneUtils.checkResponseFlag(getActivity(), result);
                        if (data != null) {
                            mMStatusDialog.show("\uD81B\uDF07\uD81B\uDF73\uD81B\uDF3B\uD81B\uDFD4\uD81B\uDF3D\uD81B\uDFD3\uD81B\uDF16\uD81B\uDF54\uD81B\uDF3A\uD81B\uDFBD\uD81B\uDF0A\uD81B\uDF58",null);
                            onRefresh();
                        }
                    }
                });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);
    }

    @Subscribe(code = Constants.RXBUS_CODE_REFRESH_CONTACT, threadMode = ThreadMode.MAIN)
    public void refreshContact(CommonEvent event) {
        MyLog.e("yang", "msg==" + event.getMsg());
        onRefresh();
    }
}
